// templates/deliver/pages/location/location.js
import Notify from '@vant/weapp/notify/notify';
import Dialog from '@vant/weapp/dialog/dialog';
import { clearUserLocalStorage } from "../../../../utils/util";
const { authorization } = require('../../../../utils/location')
const app = getApp();


Page({

    /**
     * 页面的初始数据
     */
    data: {
        orders: [],
        markers: [],
        selected_ids: [],
        select_all_status: false,
        refund_type_id: 0,
        refund_type_list: [
            { text: '换货', value: '换货' },
            { text: '退货退款', value: '退货退款' },
            { text: '仅退款', value: '仅退款' }
        ],
        count: 0,
        area: '', //获取区域
        scale: 12.1,
        activeNames: ['1'],// 打开信息 按钮
        latitude: 0,   //获取当前位置
        longitude: 0,
        selected_delivery_man_index: 0,
        dispatch_delivery_man_id: 0,
        checked: true,
        image: '/templates/deliver/img/business.png',
    },

    /**
     * 生命周期函数--监听页面加载
     */ async onLoad(options) {
        let now = (new Date().getTime()) / 1000;
        let expiration_time = wx.getStorageSync('expiration_time')


        console.log('session:', app.session)
        // wx.setStorageSync('viewDeliveryDate', new Date())
        let current_delivery_man_id = app.session.current_delivery_man_id ?? 0
        let current_delivery_district_id = app.session.current_delivery_district_id ?? 0
        if (now > expiration_time) {
            console.log('已过登录有效期!')
            app.session = {}
            clearUserLocalStorage()
            wx.reLaunch({
                url: '/pages/selectID/selectID',
            })
        }

        /*if (now > expiration_time) {
            wx.reLaunch({
                url: '/pages/login/login',
            })
        }*/
        let delivery_man_list = app.session.delivery_man_list
        let delivery_district_list = app.session.delivery_district_list
        let access_token = app.session.access_token
        let delivery_man = app.session.delivery_man
        let delivery_district = wx.getStorageSync('delivery_district')
        this.setData({
            access_token,
            delivery_man,
            delivery_district,
            delivery_district_list,
            delivery_man_list,
            current_delivery_district_id,
            delivery_man: delivery_man,
            current_delivery_man_id
        })
        this.get_waiting_delivery()
    },

    onCheck(e) {
        let orders = this.data.orders
        let selected_ids = e.detail
        let select_all_status = false
        if (selected_ids.length === orders.length) {
            select_all_status = true
        }
        this.setData({
            selected_ids,
            select_all_status
        })
    },

    onTapMarker(e) {
        const markerId = parseInt(e.detail.markerId)
        const markers = this.data.markers;

        console.log(markerId)
        const marker = markers.find(m => m.id === markerId); // 根据地图标记的 id 找到对应的 marker
        console.log(marker)
        if (marker) {
            const query = wx.createSelectorQuery();
            query.select(marker.select_id).boundingClientRect(); // 根据订单 id 找到对应的卡片
            query.exec(function (res) {
                console.log('res', res)
                const cardRect = res[0];
                if (cardRect) {
                    wx.pageScrollTo({
                        scrollTop: cardRect.top,
                    });
                }
            });
        }
    },

    tap_avatar(e) {
        console.log(e)
        wx.pageScrollTo({
            scrollTop: 0,
            duration: 300
        })
        let latitude = e.currentTarget.dataset.latitude //获取传递的id参数
        let longitude = e.currentTarget.dataset.longitude //获取传递的id参数
        this.setData({
            'scale': 17,
        })
        this.map = wx.createMapContext('locationM', this)
        this.map.moveToLocation({
            longitude: Number(longitude),
            latitude: Number(latitude),
            success: function () {

            }
        })
    },

    select_all(event) {
        let orders = this.data.orders
        let selected_ids = []
        for (let i = 0; i < orders.length; i++) {
            selected_ids.push(String(orders[i]['id']))
        }
        this.setData({
            selected_ids: selected_ids,
            select_all_status: event.detail,
        })
        if (this.data.select_all_status === false) {
            this.setData({
                selected_ids: [],
            })
        }
        //console.log(this.data.result)
    },

    on_delivery_district_dropdown_change(e) {
        const current_delivery_district_id = e.detail;
        this.setData({
            current_delivery_district_id: current_delivery_district_id,
        });
        wx.setStorageSync('current_delivery_district_id', current_delivery_district_id);
        this.get_waiting_delivery();
    },
    async get_current_location() {
        let res = await authorization()
        console.log("authorization res", res)
        this.setData({
            'longitude': res.longitude,
            'latitude': res.latitude,
        })
        /*
        this.map.moveToLocation({
            longitude: Number(this.data.longitude),
            latitude: Number(this.data.latitude),
            success: function () {
                console.log("成功将地图中心移到定位点")
            }
        })
        */
    },



    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {



    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {



    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },
    onDisplay({
        detail
    }) {
        console.log({
            detail
        })
        var markers = this.data.markers;
        wx.showModal({
            title: '提示',
            content: '是否切换开关？',
            success: (res) => {
                console.log(res.confirm)
                if (!detail) {
                    for (var i = 0; i < markers.length; i++) {
                        this.setData({
                            ["markers[" + i + "].callout.display"]: 'BYCLICK',
                            checked: detail
                        });
                    }
                    this.setData({
                        checked: detail
                    });
                } else {
                    for (var i = 0; i < markers.length; i++) {
                        this.setData({
                            ["markers[" + i + "].callout.display"]: 'ALWAYS',

                        });
                    }
                    this.setData({
                        checked: detail
                    });
                }

            },
        });
    },

    onChangeShowCallout(event) {

        const {
            value
        } = event.detail;
        console.log(value)
        this.data.markers.forEach((item, index) => {

            if (value) {
                this.setData({

                    ["markers[" + index + "].callout.display"]: 'ALWAYS'

                });
            } else {
                this.setData({

                    ["markers[" + index + "].callout.display"]: 'BYCLICK'

                });
            }

        })


    },

    async deliver() {
        const that = this

        let current_delivery_man_id = that.data.current_delivery_man_id
        let current_delivery_delivery_district_id = that.data.current_delivery_delivery_district_id
        let current_delivery_district_id = that.data.current_delivery_district_id

        console.log(current_delivery_district_id, current_delivery_man_id)

        if ((current_delivery_district_id < 1) || (current_delivery_man_id < 1)) {
            Notify({
                type: 'warning',
                message: '请选择区域或者配送员再发货'
            });
            return
        }

        let selected_ids = that.data.selected_ids

        wx.request({
            url: app.globalData.API + '/delivery/index/deliver',
            header: {
                'Content-Type': 'application/json',
                "x-api-key": this.data.access_token,
            },
            method: "POST",
            data: {
                current_delivery_district_id,
                current_delivery_man_id,
                current_delivery_delivery_district_id,
                selected_ids
            },
            success(res) {
                if (res.data.code == 200) {

                }
            }
        })
    },

    async get_waiting_delivery() {


        const that = this
        await that.get_current_location()
        wx.showLoading({
            title: '加载中...',
            mask: true
        });
        wx.request({
            url: app.globalData.API + '/delivery/index/refund-orders',
            header: {
                'Content-Type': 'application/json',
                "x-api-key": this.data.access_token,
            },
            method: "POST",
            data: {

            },

            success(res) {
                wx.hideLoading();
                if (res.data.code == 200) {
                    let orders = res.data.data.orders
                    console.log(orders)
                    let markers = []
                    for (let i = 0; i < orders.length; i++) {
                        const longitude = orders[i].longitude; // 经度
                        const latitude = orders[i].latitude; // 纬度
                        orders[i].latitude = latitude
                        orders[i].longitude = longitude
                        orders[i].distance = that.getDistance(latitude, longitude, that.data.latitude, that.data.longitude)
                    }
                    orders.sort((a, b) => a.distance - b.distance);

                    for (let i = 0; i < orders.length; i++) {
                        markers.push({
                            iconPath: "../../img/icon-hc.png",
                            id: 900000000 + parseInt(orders[i].order_id),
                            order_id: orders[i].order_id,
                            select_id: `#card-${orders[i].order_id}`,
                            latitude: orders[i].latitude,
                            longitude: orders[i].longitude,
                            width: 23,
                            height: 23,
                            callout: {
                                content: orders[i].contact,
                                fontSize: 14,
                                padding: true,
                                color: '#444',
                                display: 'ALWAYS',
                                textAlign: 'center',
                                borderRadius: 5,
                                bgColor: '#ffffff'
                            },
                        })

                    }

                    that.setData({
                        markers: markers,
                        orders: orders
                    })
                    Notify({
                        type: 'success',
                        message: '数据加载完成'
                    });

                }
            }
        })
    },
    //根据距离计算远近
    sort_orders(orders) {
        let arr = newArray;
        let s = "";
        for (var i = 1; i < arr.length; i++) {
            for (var j = i; j > 0; j--) {
                if (arr[j].distance > arr[j - 1].distance) {
                    s = arr[j];
                    arr[j] = arr[j - 1];
                    arr[j - 1] = s;
                }
            }
        }
        return newArray.reverse();

    },
    // 经纬度计算距离

    getDistance(lat1, lng1, lat2, lng2) {
        var radLat1 = lat1 * Math.PI / 180.0;
        var radLat2 = lat2 * Math.PI / 180.0;
        var a = radLat1 - radLat2;
        var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
        var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
            Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
        s = s * 6378.137;// EARTH_RADIUS;
        s = Math.round(s * 10000) / 10000;
        s = s.toFixed(2);
        return parseFloat(s);
    },


    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
        //this.get_waiting_delivery()
        //wx.stopPullDownRefresh()

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },
    //点击导航事件
    //点击导航事件
    getLocation(e) {
        const that = this
        let index = e.currentTarget.dataset['index']; //获取传递的参数
        let order = that.data.orders[index]

        var address = order.address
        var contact = order.contact
        var mobile = order.mobile
        var latitude = order.latitude
        var longitude = order.longitude
        wx.openLocation({
            latitude: Number(latitude), //要去的纬度-地址 一定不要使数字
            longitude: Number(longitude), //要去的经度-地址
            address: address,
            name: contact + '/' + mobile,
            scale: 15
        })
    },
    //点击展开
    onAddress(event) {
        this.setData({
            activeNames: event.detail,
        });
    },
    generateAfterSalesOrder: function (e) {
        const { address, contact, mobile, customer_remark, remark, price, customer_cause, hj_order_no } = e.currentTarget.dataset;
        const orderData = {
            customer_address: address,
            customer_name: contact,
            customer_mobile: mobile,
            customer_remarks: customer_cause + customer_remark,
            remark: remark,
            price: price,
            hj_order_no: hj_order_no,

        }
        console.log(orderData);
        const orderDataJson = encodeURIComponent(JSON.stringify(orderData));
        wx.navigateTo({
            url: `/templates/deliver/pages/aftermarket/aftermarket?orderData=${orderDataJson}`
        });
    },
    // viewOrderGoods(event) {
    //     let order_no = event.target.dataset.order_no;
    //     wx.navigateTo({
    //         url: '/templates/deliver/pages/orderGoods/orderGoods?order_no=' + order_no,
    //     })
    // },
    parseJsonOrEmptyArray(jsonString) {
        try {
            const parsed = JSON.parse(jsonString);
            if (Array.isArray(parsed)) {
                // 检查数组元素的结构，并进行转换
                return parsed.map(item => {
                    if (typeof item === 'object' && 'url' in item) {
                        return item; // 已经是 { url: 'https://xxxxx' } 格式
                    } else if (typeof item === 'object' && item.url) {
                        return item.url; // 处理 { url: { url: 'https://xxxxx' } } 格式
                    } else {
                        return {}; // 无效的对象格式，返回空对象
                    }
                });
            } else {
                return [];
            }
        } catch (e) {
            return [];
        }
    },
    // ballPopup(e) {
    //     let that = this
    //     let index = parseInt(e.currentTarget.dataset.index)

    //     let current_order_id = e.currentTarget.dataset.order_id //获取传递的id参数
    //     let current_order = this.data.orders[index];
    //     current_order.delivery_photo = that.parseJsonOrEmptyArray(current_order.delivery_photo)
    //     this.setData({
    //         show_popup: true,
    //         current_order_id,
    //         current_order
    //     }) //打开弹窗
    // },
    onPopupClose() {
        this.setData({
            show_popup: false,
        })
    },
    onRemarkInput(e) {
        let that = this
        let value = e.detail;
        let current_order = that.data.current_order
        current_order.remark = value
        this.setData({
            current_order
        });
    },
    updateRefundOrderStatus() {

        let that = this
        let current_order = that.data.current_order
        let refund_type_id = that.data.refund_type_id
        console.log("===========", refund_type_id)
        if ((refund_type_id === undefined) || (refund_type_id === 0)) {
            Notify({
                type: 'warning',
                message: '请选择售后类型'
            });
            return
        }
        console.log(current_order.delivery_remark)
        let order_id = current_order.order_id
        let remark = current_order.remark
        wx.request({
            url: app.globalData.API + '/delivery/index/update-refund-order-status',
            header: {
                'Content-Type': 'application/json',
                "x-api-key": this.data.access_token,
            },
            method: "POST",
            data: {
                order_id,
                refund_type_id,
                remark
            },
            success(res) {
                if (res.data.code === 200) {
                    Notify({
                        type: 'success',
                        message: '处理完成'
                    });
                    that.onPopupClose()
                    that.get_waiting_delivery()
                } else {
                    Notify({
                        type: 'success',
                        message: '处理失败'
                    });
                    that.onPopupClose()
                }
            }
        })
    },
    on_dropdown_change(e) {
        const dispatch_delivery_man_id = e.detail;
        console.log(dispatch_delivery_man_id);

        //根据 dispatch_delivery_man_id 找出delivery_man在 delivery_man_list 的索引值
        const selected_delivery_man_index = this.data.delivery_man_list.findIndex(d => d.value === dispatch_delivery_man_id);

        this.setData({
            selected_delivery_man_index,
            dispatch_delivery_man_id
        });
    },
    on_dispatch_dropdown_change(e) {
        const dispatch_delivery_man_id = e.detail;
        const delivery_man = this.data.delivery_man_list.find(d => d.value === dispatch_delivery_man_id);
        if (delivery_man) {
            this.setData({
                dispatch_delivery_man_id
            });
        }
    },

    on_refund_dropdown_change(e) {
        const refund_type_id = e.detail;
        const refund_type = this.data.refund_type_list.find(d => d.value === refund_type_id);
        if (refund_type) {
            this.setData({
                refund_type_id
            });
        }
    },

})
